//
//  YJMMainTabBar.swift
//  Weibo
//
//  Created by 杨军民 on 16/7/18.
//  Copyright © 2016年 杨军民. All rights reserved.
//

import UIKit

class YJMMainTabBar: UITabBar {
    
    //定义闭包属性
    var composeCallBlock: (() ->Void)?
    
 //懒加载按钮
    lazy var composeButton : UIButton = {
        let button = UIButton (type: UIButtonType.Custom)
        
        //设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //添加到View中
        self.addSubview(button)
        
        //注册点击事件  TouchUpInside：触摸
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
    //控件的数量
    let itemCount = 5

    override func layoutSubviews() {
        super.layoutSubviews()
        
        //计算每一个按钮的宽度
        let itemWidth = self.frame.width / CGFloat(itemCount)
        
        
        //遍历所有的item
        var index = 0
        for item in self.subviews {
            //过滤，是UITabBarView的才需要选中frame
            let cls = NSClassFromString("UITabBarButton")!
            if item .isKindOfClass(cls){
                item.frame = CGRect(x: CGFloat(index) * itemWidth, y: 0 , width: itemWidth, height: self.frame.height)
                
                index++
                //判断要是到第二个的时候就往后移动一个位置
                if index == 2 {
                    index++
                }
            }
        }
       //设置
        composeButton.frame = CGRect(x: 2 * itemWidth, y: 0, width: itemWidth, height: self.frame.height)
    }
    
    //MARk - 点击事件
    func composeClick() ->Void {
        print("composeClick")
        composeCallBlock?()
    }
}
